package org.example;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.List;

public class EmployeeManagementGUI extends JFrame {
    private JTextField nameField;
    private JTextField idNumberField;
    private JTable employeeTable;
    private EmployeeInfoDAO employeeDAO;

    public EmployeeManagementGUI() {
        employeeDAO = new EmployeeInfoDAO();

        // 先显示登录界面
        if (!showLoginDialog()) {
            JOptionPane.showMessageDialog(this, "登录失败，请检查用户名和密码！", "登录错误", JOptionPane.ERROR_MESSAGE);
            System.exit(0);
        }

        setTitle("员工管理系统");
        setSize(600, 400);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new BorderLayout());

        JPanel inputPanel = createInputPanel();
        add(inputPanel, BorderLayout.NORTH);

        employeeTable = new JTable();
        updateTableData();
        JScrollPane scrollPane = new JScrollPane(employeeTable);
        add(scrollPane, BorderLayout.CENTER);

        JPanel buttonPanel = createButtonPanel();
        add(buttonPanel, BorderLayout.SOUTH);
    }

    // 显示登录对话框的方法
    private boolean showLoginDialog() {
        JDialog dialog = new JDialog(this, "登录", true);
        dialog.setLayout(new BorderLayout());
        dialog.setSize(300, 200);

        JPanel panel = new JPanel();
        panel.setLayout(new GridLayout(3, 2));

        JLabel usernameLabel = new JLabel("用户名:");
        JTextField usernameField = new JTextField();
        JLabel passwordLabel = new JLabel("密码:");
        JPasswordField passwordField = new JPasswordField();

        panel.add(usernameLabel);
        panel.add(usernameField);
        panel.add(passwordLabel);
        panel.add(passwordField);

        JButton loginButton = new JButton("登录");
        loginButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String username = usernameField.getText();
                char[] passwordChars = passwordField.getPassword();
                String password = new String(passwordChars);
                if (authenticateUser(username, password)) {
                    dialog.dispose();
                } else {
                    JOptionPane.showMessageDialog(dialog, "用户名或密码错误，请重新输入！", "登录错误", JOptionPane.ERROR_MESSAGE);
                }
            }
        });

        JPanel buttonPanel = new JPanel();
        buttonPanel.add(loginButton);

        dialog.add(panel, BorderLayout.CENTER);
        dialog.add(buttonPanel, BorderLayout.SOUTH);
        dialog.setLocationRelativeTo(this);
        dialog.setVisible(true);

        return true;  // 如果登录成功，这里会返回true（实际是在内部验证成功后关闭对话框，外部判断对话框已关闭来当作登录成功的依据）
    }

    // 验证用户的方法，连接数据库检查用户名和密码是否匹配
    private boolean authenticateUser(String username, String password) {
        try (Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/employee_management", "root", "123456");
             PreparedStatement statement = connection.prepareStatement("SELECT * FROM users WHERE username =? AND password =?")) {
            statement.setString(1, username);
            statement.setString(2, password);
            ResultSet resultSet = statement.executeQuery();
            return resultSet.next();
        } catch (Exception ex) {
            ex.printStackTrace();
            return false;
        }
    }

    private JPanel createInputPanel() {
        JPanel panel = new JPanel();
        panel.setLayout(new GridLayout(2, 2));

        JLabel nameLabel = new JLabel("员工姓名:");
        panel.add(nameLabel);
        nameField = new JTextField();
        panel.add(nameField);

        JLabel idNumberLabel = new JLabel("员工身份证号:");
        panel.add(idNumberLabel);
        idNumberField = new JTextField();
        panel.add(idNumberField);

        return panel;
    }

    private JPanel createButtonPanel() {
        JPanel panel = new JPanel();

        JButton addButton = new JButton("添加员工");
        addButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                addEmployee();
            }
        });
        panel.add(addButton);
        return panel;
    }

    private void addEmployee() {
        String name = nameField.getText();
        String idNumber = idNumberField.getText();
        EmployeeInfo employee = new EmployeeInfo();
        employee.setName(name);
        employee.setIdNumber(idNumber);
        employeeDAO.addEmployee(employee);
        clearFields();
        updateTableData();
    }

    private void clearFields() {
        nameField.setText("");
        idNumberField.setText("");
    }

    private void updateTableData() {
        List<EmployeeInfo> employees = employeeDAO.getAllEmployees();
        String[] columnNames = {"员工编号", "姓名", "身份证号"};
        Object[][] data = new Object[employees.size()][3];
        for (int i = 0; i < employees.size(); i++) {
            EmployeeInfo employee = employees.get(i);
            data[i][0] = employee.getEmployeeId();
            data[i][1] = employee.getName();
            data[i][2] = employee.getIdNumber();
        }
        employeeTable.setModel(new JTable(data, columnNames).getModel());
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new EmployeeManagementGUI().setVisible(true);
            }
        });
    }
}